import Vue from 'vue'
import VueRouter from 'vue-router'
import Table from '../components/Table.vue'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome.vue'
import Users from '../components/user/Users.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children:[
      {path: '/welcome', component: Welcome},
      {path: '/users', component: Users}
    ]
  },
  {
  
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  
  {
    path: '/table',
    component: Table
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import( /* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  routes
})

//挂载路由导航守卫
router.beforeEach((to, from, next) => {
  //如果用户访问登录页，直接放行。
  if (to.path === '/login') return next();

  //从sessionStorage中获取到保存的token值
  const tokenStr = window.sessionStorage.getItem('token');
  //没有token, 强制跳转到登陆页
  if (!tokenStr) return next('/login');

  next();
})

export default router